<?php

class Blog_Message_Form {

	protected static $_instance;

	/**
	 *
	 * @var Zend_Form
	 */
	protected $form;
	protected $code;

	/**
	 * 
	 * @return Blog_Message_Sql
	 */
	public static function getInstance() {
		if (null === self::$_instance) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	public function setForm(Zend_Form $form) {
		$this->form = $form;

		return $this;
	}

	protected function parse() {
		$Messages = $this->form->getMessages();
		$Translate = require APPLICATION_PATH . '/configs/form.message.php';
		$ReturnMessages = array();
		foreach ($Messages as $Name => $Errors) {
			foreach ($Errors as $ErrorType => $ErrorMessage) {
				$Label = $this->form->getElement($Name)->getLabel() ? $this->form->getElement($Name)->getLabel() : $this->form->getElement($Name)->getAttrib('placeholder');
				if (is_numeric($ErrorType)) {
					$Message = $ErrorMessage;
				} else {
					switch ($ErrorType) {
						case Zend_Validate_StringLength::INVALID:
							if (null != ($a = $this->form->getElement($Name)->getValidator('StringLength'))) {
								$Message = sprintf($Translate[$ErrorType], $Label, $a->getMin(), $a->getMax());
								break;
							}
						case Zend_Validate_StringLength::TOO_SHORT:
							if (null != ($a = $this->form->getElement($Name)->getValidator('StringLength'))) {
								$Message = sprintf($Translate[$ErrorType], $Label, $a->getMin());
								break;
							}
						case Zend_Validate_StringLength::TOO_LONG:
							if (null != ($a = $this->form->getElement($Name)->getValidator('StringLength'))) {
								$Message = sprintf($Translate[$ErrorType], $Label, $a->getMax());
								break;
							}
						case Zend_Validate_File_Extension::FALSE_EXTENSION:
							if (null != ($a = $this->form->getElement($Name)->getValidator('Extension'))) {
								$Message = sprintf($Translate[$ErrorType], implode(', ' , $a->getExtension()));
								break;
							}
						default:
							$Message = sprintf($Translate[$ErrorType], $Label);
					}
				}
				array_push($ReturnMessages, $Message);
			}
		}


		return $ReturnMessages;
	}

	public function getMessage($index) {
		$Message = $this->parse();
		if (!$Message) {
			return $this->message;
		}

		return $Message;
	}

	public function getMessages() {
		return $this->parse();
	}

}
